
import axios from 'axios'
import router from './index'
// import store from '@/store'
import { Toast } from 'mand-mobile'
axios.defaults.timeout = 30000
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true

// HTTPrequest拦截
axios.interceptors.request.use(config => {
  config.headers.device = 'app-h5'
  config.headers.token = '5f171d76-c72d-4231-95f2-e7604a4b935a'
  return config
}, error => {
  return Promise.reject(error)
})

// HTTPresponse拦截
axios.interceptors.response.use(res => {
  const status = Number(res.status) || 200
  const message = res.data.msg || res.data.message || '未知错误'
  if (status === 401 || res.data.code === 20000 || res.data.code === 0) {
    Toast.failed(message)
    router.push({ path: '/login' })
    // store.dispatch('Logout').then(() => {
    //   router.push({ path: '/login' })
    // })
    return
  }

  if (status !== 200 || Number(res.data.code) !== 10000) {
    Toast.failed(message)
    return Promise.reject(new Error(message))
  }

  return res
}, error => {
  Toast.failed(error)
  return Promise.reject(new Error(error))
})

export default axios
